/**
 * 
 */
package durak.client.control;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import durak.common.control.GameCommand;
import durak.common.control.GameCommand.CommandType;
import durak.common.model.Cards;

/**
 * @author miri
 * 
 */
public class ClientSessionControl implements Runnable {

	private Socket clientSocket;
	ObjectOutputStream outStream;
	ObjectInputStream inputStream;
	private String playerName;
	private ClientPlayerControl playerControl;

	/**
	 * 
	 */
	public ClientSessionControl(InetAddress address, int port, String playerName, ClientPlayerControl playerControl) {
		this.playerName = playerName;
		this.playerControl = playerControl;
		try {
			clientSocket = new Socket(address, port);
			outStream = new ObjectOutputStream(this.clientSocket.getOutputStream());
			inputStream = new ObjectInputStream(this.clientSocket.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		GameCommand firstCommand = new GameCommand();
		firstCommand.setCommandType(GameCommand.CommandType.C2S_JOIN);
		firstCommand.setPlayerName(playerName);
		try {
			outStream.writeObject(firstCommand);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		GameCommand serverCommand;
		try {
			while ((serverCommand = (GameCommand) inputStream.readObject()) != null) {
				playerControl.handleReceivedMessageFromServer(this, serverCommand);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendC2SCommand(GameCommand command) {
		try {
			outStream.reset();
			outStream.writeObject(command);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendResponseToAttack(Cards cards) {
		GameCommand commandToServer = new GameCommand(CommandType.C2S_ATTACKED, cards);
		sendC2SCommand(commandToServer);

	}

	public void sendResponsePassAttack() {
		GameCommand commandToServer = new GameCommand(CommandType.C2S_PASS_ATTACK);
		sendC2SCommand(commandToServer);

	}
	
	public void sendResponseWithdraw() {
		GameCommand commandToServer = new GameCommand(CommandType.C2S_WITHDRAWN);
		sendC2SCommand(commandToServer);

	}


	public void sendQuit() {
		GameCommand commandToServer = new GameCommand(CommandType.C2S_QUIT);
		sendC2SCommand(commandToServer);
	}
}
